<template>
  <ContentWrap :no-padding="true">
    <IFrame
      id="iframe" :class="loading && 'fixed top-0 left-0 right-0'"
      :style="`height:${loading ? '100%' : iframeH}`" :src="src"/>
  </ContentWrap>

</template>
<script lang="ts" setup>
import {getAccessToken, getTenantId} from "@/utils/auth";

defineOptions({name: 'DataEase'})

const route = useRoute();

const router = useRouter();

const height = ref('')

const iframe = ref(null)

const messageId = randomString(16)

const loading = ref(false)

const whiteRoute = ['/report/dashboard','/report/dvCanvas', '/report/dataset-form'];

//默认初始化参数 可扩展
const config = {
  header: {
    'Authorization': 'Bearer ' + getAccessToken(),
    'X-De-Token': getAccessToken(),
    'Tenant-Id': getTenantId(),
  },
  basePath: '',
  messageId: messageId,
}


watch(
  () => route.path,
  (path) => {
    if (whiteRoute.includes(path)) {
      loading.value = true
    }
  },
  {
    immediate: true
  }
)

const iframeH = computed(() => {
  if (loading.value) {
    return document.documentElement.clientHeight + 'px'
  }
  return height.value ? height.value + 'px' : ''
})

const BASE_URL = import.meta.env.VITE_BASE_URL

const src = computed(() => {
  const params = route.query.params

  console.log(route.path)
  const lastParts = route.path.split('/');
  const path = lastParts.slice(2).join('/');

  // return 'http://10.126.16.160:8080/#/' + path + '?messageId=' + messageId + (params ? '&' + params : '')
  return BASE_URL + '/index.html#/' + path + '?messageId=' + messageId + (params  ? '&' + params : '')
})


onMounted(() => {
  window.addEventListener('message', function (event) {
    let {type, data} = event.data
    switch (type) {
      case "created":
        sendEvent(data.callback, {
          ...config, ...data
        })
        break;
      case "setHeight":
        height.value = data.h
        break
      case "urlJump":
        router.push({
          path: '/report' + data.path,
          query: data.query ? {params: data.query} : undefined
        })
        break
      case "setPop":
        showLoading(data)
        break
      default:
        break;
    }
  })
})

const showLoading = (data) => {
  loading.value = data.state;
  if (data.state) {
    const divInPage = document.getElementById('iframe') as HTMLDivElement;
    const divRect = divInPage.getBoundingClientRect();
    const top = divRect.top.toFixed(0);
    const left = divRect.left.toFixed(0);
    sendEvent(data.callback, {
      top, left, ...data
    })
  } else {
    sendEvent(data.callback, {
      ...data
    })
  }
}

const sendEvent = (type, data) => {
  const iframeWindow = window.frames[0];
  nextTick(() => {
    iframeWindow.postMessage({type, data}, '*')
  });
}

function randomString(length: number = 16): string {
  const chars = "0123456789qwertyuioplkjhgfdsazxcvbnm"
  let result = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    result += chars.charAt(randomIndex);
  }
  return result;
}
</script>
